<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\facade\View;
use think\exception\ValidateException;
use app\admin\BaseController;
use app\admin\model\AdminGroup;
use app\admin\model\AdminUser as UserModel;
use app\admin\validate\AdminUser as UserValidate;
/**
 * 管理员
 */
class AdminUser extends BaseController
{
    /**
     * 显示资源列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $input = input();
            $order = $input['order'] === 'ascending' ? 'asc' : 'desc';
            $count = UserModel::withSearch(['keyword','date'], $input)->count();
            $data  = UserModel::withSearch(['keyword','date'], $input)
            ->with(['group'])
            ->order($input['prop'], $order)
            ->page($input['page'], $input['pageSize'])
            ->select();
            return json(['status' => 'success','message' => '', 'data' => $data, 'count' => $count]);
        } else {
            $group = AdminGroup::field('id,pid,title')->where('status', 1)->select();
            $event = event("UserAdminField");
            $field = [];
            foreach ($event as $key => $val) {
                foreach ($val as $k => $v) {
                    array_push($field, $v);
                }
            }
            View::assign([
                'group'  => $group, 
                'field'  => $field,
            ]);
            return View::fetch();
        }
    }

    /**
     * 保存新建的资源
     */
    public function save()
    {
        try {
            $input = input();
            validate(UserValidate::class)->scene('save')->check($input);
            $account = UserModel::where('account', $input['account'])->value('id');
            $email   = UserModel::where('email', $input['email'])->value('id');
            if (! $account) {
                if (! $email) {
                    $date  = date('Y-m-d H:i:s');
                    UserModel::create([
                        'group_id'    => $input['group_id'],
                        'nickname'    => $input['nickname'],
                        'sex'         => $input['sex'],
                        'email'       => $input['email'],
                        'account'     => $input['account'],
                        'password'    => $input['password'],
                        'cover'       => $input['cover'],
                        'login_ip'    => "",
                        'login_count' => 0,
                        'login_time'  => $date,
                        'update_time' => $date,
                        'create_time' => $date,
                        'status'      => $input['status'],
                        'field'       => $input['field'],
                    ]);
                    return json(['status' => 'success', 'message' => '新增成功']);
                } else {
                    return json(['status' => 'error', 'message' => '邮箱号已经存在！']);
                }
            } else {
                return json(['status' => 'error', 'message' => '账号已经存在！']);
            }
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 保存更新的资源
     */
    public function update()
    {
        try {
            $input = input();
            validate(UserValidate::class)->check($input);
            $save  = UserModel::find($input['id']);
            $save->update_time = date('Y-m-d H:i:s');
            $save->group_id = $input['group_id'];
            $save->nickname = $input['nickname'];
            $save->sex      = $input['sex'];
            $save->cover    = $input['cover'];
            $save->status   = $input['status'];
            $save->field    = $input['field'];
            if (! empty($input['password'])) {
                $save->password = $input['password'];
            }
            $save->save();
            return json(['status' => 'success', 'message' => '修改成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 删除指定资源
     */
    public function delete()
    {
        try {
            $input = input();
            validate(UserValidate::class)->scene('delete')->check($input);
            UserModel::destroy($input['ids']);
            return json(['status' => 'success', 'message' => '删除成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }
    
    /**
     * 管理员日志
     */
    public function log()
    {
        if ($this->request->isPost()) {
            $list  = $this->request->businessLog();
            $data  = $list['data'];
            $count = $list['count'];
            return json(['status' => 'success','message' => '', 'data' => $data, 'count' => $count]);
        } else {
            return View::fetch();
        }
    }

    /**
     * 个人中心
     */
    public function personal() 
    {
        if ($this->request->isPost()) {
            $list  = $this->request->businessLog(true);
            $data  = $list['data'];
            $count = $list['count'];
            return json(['status' => 'success','message' => '', 'data' => $data, 'count' => $count]);
        } else {
            return View::fetch();
        }
    }
    
    /**
     * 个人信息修改
     */
    public function personalUpdate()
    {
        try {
            $input = input();
            validate(UserValidate::class)->scene('update')->check($input);
            $save  = UserModel::with(['group'])->find($this->request->userInfo['id']);
            $email = UserModel::where('email',$input['email'])->where('id', '<>', $save->id)->value('id');
            if (empty($email)) {
                $save->nickname = $input['nickname'];
                $save->email    = $input['email'];
                $save->cover    = $input['cover'];
                $save->update_time = date('Y-m-d H:i:s');
                if (! empty($input['password'])) {
                    $save->password = $input['password'];
                }
                $save->save();
                session('admin_user',$save);
                return json(['status' => 'success', 'message' => '修改成功']);
            } else {
                return json(['status' => 'error', 'message' => '邮箱号已经存在！']);
            }
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }
}
